<template>
  <div id="picture-upload">
    <a-upload
      list-type="picture-card"
      :show-upload-list="false"
      :custom-request="handleUploadChange"
      :before-upload="beforeUpload"
    >
      <!-- 上传成功预览（仅在父组件 picture 存在时显示） -->
      <img
        v-if="props.picture?.url && !isUploading"
        :src="props.picture?.url"
        alt="上传预览"
        class="uploaded-img"
      />

      <!-- 上传中状态 -->
      <div v-else class="upload-container">
        <div class="loading-state" v-if="isUploading">
          <div class="progress-wrap">
            <div
              class="progress-bar"
              :style="{ width: uploadProgress + '%' }"
            ></div>
          </div>
          <div class="progress-text">上传中... {{ uploadProgress }}%</div>
        </div>

        <!-- 初始/错误状态 -->
        <div v-else class="initial-state">
          <PlusOutlined class="plus-icon" />
          <div class="ant-upload-text">点击或拖拽上传</div>
        </div>
      </div>
    </a-upload>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { UploadProps, UploadFile } from 'ant-design-vue'
import { uploadPictureUsingPost } from '@/api/pictureController'

const isUploading = ref<boolean>(false)
const uploadProgress = ref<number>(0)

// 父组件 props
interface Props {
  picture?: API.PictureVO | null;
  spaceId?: number;
  onSuccess?: (newPicture: API.PictureVO) => void;
}

const props = defineProps<Props>()

// 上传逻辑
const handleUploadChange = async ({ file }: any) => {
  isUploading.value = true
  uploadProgress.value = 0

  try {
    // 模拟进度（实际项目替换为真实进度回调）
    const progressTimer = setInterval(() => {
      if (uploadProgress.value < 100) {
        uploadProgress.value += 10
      } else {
        clearInterval(progressTimer)
      }
    }, 500)

    // 上传时传递 spaceId
    const params: API.PictureUploadDTO = props.picture ? { id: props.picture.id } : {}
    params.spaceId = props.spaceId

    const res = await uploadPictureUsingPost(
      params,
      {},
      file
    )

    clearInterval(progressTimer)
    // @ts-ignore
    if (res.data?.code === 0 && res.data?.data) {
      message.success('上传成功')
      // @ts-ignore
      props.onSuccess?.(res.data.data)
    } else {
      // @ts-ignore
      message.error('上传失败: ' + res.data?.message)
    }
  } catch (e) {
    console.error('上传失败:', e)
    message.error('上传失败，请重试')
  } finally {
    isUploading.value = false
    uploadProgress.value = 0
  }
}

// 上传前校验
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('仅支持上传图片文件！')
    return false
  }

  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！')
    return false
  }

  return true
}
</script>

<style scoped>
#picture-upload :deep(.ant-upload) {
  width: 100% !important;
  height: 100% !important;
  min-height: 200px;
  background-color: #e8f5e9; /* 浅绿色背景 */
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 上传成功预览图 */
.uploaded-img {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
}

/* 上传容器 */
.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 40px;
}

/* 上传中状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.progress-wrap {
  width: 80%;
  height: 8px;
  background-color: #d3e9d4;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 16px;
}

.progress-bar {
  height: 100%;
  background-color: #4caf50;
  transition: width 0.3s ease;
}

.progress-text {
  color: #666;
  font-size: 14px;
}

/* 初始状态 */
.initial-state {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.plus-icon {
  font-size: 48px;
  color: #999;
  margin-bottom: 12px;
}

.ant-upload-text {
  color: #666;
}
</style>
